package cn.wizzer.app.web.modules.controllers.user;

import cn.wizzer.app.crown.modules.models.enums.SettleStatusEnum;
import cn.wizzer.app.sys.modules.services.SysMsgService;
import cn.wizzer.app.user.modules.models.User;
import cn.wizzer.app.user.modules.models.enums.EquipmentEnum;
import cn.wizzer.app.user.modules.services.CrownBetCountService;
import cn.wizzer.app.user.modules.services.UserAgentService;
import cn.wizzer.app.user.modules.services.UserService;
import cn.wizzer.app.user.modules.services.account.UserAccountRecordService;
import cn.wizzer.app.web.commons.filter.ApiTokenFilter;
import cn.wizzer.app.web.commons.ulog.annotation.ULog;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.page.Pagination;
import com.alibaba.dubbo.config.annotation.Reference;
import io.swagger.annotations.ApiParam;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.*;

import java.util.Map;

/**
 * 代理端
 */
@At("/api/agent")
@IocBean
public class ApiAgentController {

    @Inject
    private ApiUserController userController;

    @Inject
    @Reference(timeout = 60000)
    private UserAgentService agentService;

    @Inject
    @Reference
    private UserService userService;

    @Inject
    @Reference
    private CrownBetCountService agentRecordService;

    @Inject
    @Reference(retries = 3, timeout = 60000)
    private UserAccountRecordService accountRecordService;

    @Reference
    @Inject
    private SysMsgService sysMsgService;

    @Inject
    private RedisService redisService;

    /**
     * 代理登录
     *
     * @param phone
     * @param password
     * @return
     */
    @At
    @Ok("json")
    @ULog(tag = "代理登录", msg = "登录手机: ${phone}")
    public Result login(@ApiParam(required = true, value = "phone") @Param("phone") String phone,
                        @ApiParam(required = true, value = "password") @Param("password") String password) {
        Result info = userController.login(phone, password, EquipmentEnum.AGENT);
        if (info.getCode() == 0) {
            boolean agent = ((NutMap) (info.getData())).getBoolean("agent");
            if (!agent) {
                return Result.error("Permission denied,you are not an agent!");
            }
        }
        return info;
    }

    /**
     * 收入记录
     *
     * @param pageNumber
     * @param pageSize
     * @param startTime
     * @param endTime
     * @param searchKeyword
     * @return
     */
    @At
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Result accountRecord(Integer pageNumber, int pageSize, String startTime, String endTime, String searchKeyword) {
        String userId = Mvcs.getReq().getHeader("appid");
        return Result.success(agentRecordService.agentIncomeRecord(pageNumber, pageSize, startTime, endTime, searchKeyword, userId));
    }

    /**
     * 邀请统计
     *
     * @return
     */
    @At
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Result inviteCount() {
        String appid = Mvcs.getReq().getHeader("appid");
        Map result = agentService.inviteCount(appid);
        return Result.success(result);
    }

    /**
     * 子级
     *
     * @param pageNumber
     * @param pageSize
     * @param searchKeyword
     * @param startTime
     * @param endTime
     * @return
     */
    @At
    @Ok("json:full")
    @Filters(@By(type = ApiTokenFilter.class))
    public Result subUsers(@ApiParam("pageNumber") int pageNumber,
                           @ApiParam("pageSize") int pageSize, String searchKeyword, long startTime, long endTime) {
        String appid = Mvcs.getReq().getHeader("appid");

        Pagination pagination = agentService.subUsers(pageNumber, pageSize, appid, searchKeyword, startTime, endTime);
        return Result.success(pagination);
    }

    /**
     * 添加子级
     *
     * @param password
     * @param nickName
     * @param phone
     * @return
     */
    @At
    @Ok("json:full")
    @Filters(@By(type = ApiTokenFilter.class))
    @ULog(tag = "代理添加子级", msg = "子级昵称: ${nickName}, 手机号: ${phone}")
    public Result addUser(String password, String nickName, String phone) {
        String appid = Mvcs.getReq().getHeader("appid");
        User user = new User();
        user.setPassword(password);
        //not required
        user.setNickName(nickName);
        user.setPhone(phone);
        user.setInviter(appid);
        userService.insertUser(user, null);
        return Result.success();
    }

    /**
     * 修改返利比
     *
     * @return
     */
    @At
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    @ULog(tag = "代理修改返利比", msg = "子级: ${userId}, selfRate: ${selfRate}, superRate: ${superRate}")
    public Result editRate(String userId, int selfRate, int superRate) {
        if (selfRate < 0 || superRate < 0) {
            return Result.error();
        }
        String appid = Mvcs.getReq().getHeader("appid");
        agentService.editRate(userId, appid, selfRate, superRate);
        return Result.success();
    }

    /**
     * 流水
     *
     * @param pageNumber
     * @param pageSize
     * @param searchKeyword
     * @param startTime
     * @param endTime
     * @return
     */
    @At
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Result betRecords(@ApiParam("pageNumber") int pageNumber, @ApiParam("pageSize") int pageSize,
                             String searchKeyword, long startTime, long endTime,
                             String no, SettleStatusEnum status) {
        Map count = accountRecordService.count(pageNumber, pageSize, searchKeyword, startTime, endTime, no, status, Mvcs.getReq().getHeader("appid"));
        return Result.success(count);
    }

    /**
     * 流水统计
     *
     * @return
     */
    @At
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Result betCount() {
        String appid = Mvcs.getReq().getHeader("appid");
        Map result = agentRecordService.recordCount(appid);
        return Result.success(result);
    }

    /**
     * 流水统计
     *
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @At
    @Ok("json")
    @Filters(@By(type = ApiTokenFilter.class))
    public Result msg(Integer pageNumber, int pageSize) {
        Sql sql = Sqls.create("select * from sys_msg ");
        Sql countSql = Sqls.create("select count(1) from sys_msg ");
        //代理相关消息或代理公告
        Sql whereSql = Sqls.create("where delFlag = 0 and (type = 'agentAll' or (type= 'agent' and (select count(*) from sys_msg_user where msgId = sys_msg.id and delFlag =0 and userId = @userId)>0))");
        whereSql.setParam("userId", Mvcs.getReq().getHeader("appid"));

        sql.appendSourceSql(whereSql.toString());
        sql.appendSourceSql("order by opAt desc");
        countSql.appendSourceSql(whereSql.toString());
        return Result.success().addData(sysMsgService.listPage(pageNumber, pageSize, sql, countSql));
    }

}
